<template>
	<view class="">
		<uni-row v-if="config.listLayout == 'batchList' && configLoaded" style="max-height: calc(100vh - 50%);">
			<!-- 左右两侧布局列表  右边列表 -->
			<view class="retail-list-left padding-0" v-if="inPageType == 'batch-update'">

			</view>
			<view
				:class="inPageType !== 'batch-update' ? 'retail-list-right' : 'retail-list-right retail-list-right-full'">
				<!-- 全部退款不需要 -->
				<!--      <view class="">
          <view class="cu-form-group search-box">
            <view class="uni-input-box">
              <input class="uni-input" v-model="searchVal" placeholder="商品条码或名称搜索" @confirm="onSearch"/>
              <text class="cuIcon-scan"></text>
            </view>
            <button class="search-icon button bg-white" @click.stop="onSearch">
              <text class="cuIcon-search "></text>
            </button>
          </view>
        </view> -->
				<view class="retail-list-right-middle">
					<slot name="rLayoutRight">

					</slot>
					<uni-table border stripe emptyText="暂无更多数据" :stripe="false" :loading="loading">
						<!-- 表头行 -->
						<uni-tr>
							<uni-th width="auto" align="center" v-for="(headCol,index) in gridHeader" :key="index">
								{{headCol.label}}
							</uni-th>
						</uni-tr>
						<!-- 表格数据行 -->
						<uni-tr v-for="(dataRow,index) in listData" :key="index"
							v-if="config.listLayout == 'batchList'">
							<uni-td v-for="(headCol,i) in gridHeader" :key="i">
								<view class="table-td-text"
									style="width:100%;height:100%;max-width:200rem;text-align: center;justify-content: center;"
									@click.stop="onItemClick(dataRow)">
									<!-- {{dataRow[headCol.columns] ? dataRow[headCol.columns] : "-"}} -->
									<u-number-box inputWidth="80" :min="0" v-model="listData[index]['refund_num']"
										:max="listData[index].can_refund_num || listData[index].goods_num"
										v-if="editorType==='part'&&headCol.columns == 'refund_num'&&headCol.label==='退款数量'"
                    @change="onchange(index)"
                    >
									</u-number-box>
									<text
										v-else-if="editorType==='all'&&headCol.columns == 'refund_num'">{{listData[index].goods_num}}</text>
									<!-- 	<uni-easyinput primaryColor="#38c09e" style="width: 20rem;margin: 0 auto;"
										v-if="editorType==='part'&&headCol.columns == 'refund_num'&&headCol.label==='退款数量'"
										v-model="listData[index][column]" :max="listData[index].goods_num" placeholder="" type="number" /> -->
									<gStrIntercept v-else
										:defaultStr="dataRow[headCol.columns]||dataRow[headCol.columns]===0 ? dataRow[headCol.columns] : '-'"
										:len="8">
									</gStrIntercept>

								</view>
							</uni-td>
						</uni-tr>
					</uni-table>
					<rpaging v-if="config.defaultData !== 'batch-select'" :inpage="listpage"
						@on-page-change="onpagintion">
					</rpaging>
				</view>
				<view class="retail-list-right-bottom  bg-white padding">
					<!-- <view class="buttom-layout"  v-if="configLoaded">
						<view class="count-layout padding" v-if="inPageType !== 'batch-update'">
							<view class="padding-sm">{{listDataSum(config.popupColumns[0],listData)}}</view>
							<view class="padding">数量统计</view>
						</view>
						<view class="count-layout padding" v-if="inPageType !== 'batch-update'">
							<view class="padding-sm">{{listDataSum(config.popupColumns[config.popupColumns.length - 1],listData)}}</view>
							<view class="padding">金额统计</view>
						</view>
					</view>
					<view class="buttom-buttons" v-if="configLoaded && editorType !== 'detail'">
						<button :disabled="listData.length == 0" clsss="batch-submit"
							style="height: 160rpx;margin-right: 20rpx;line-height: 160rpx;min-width: 300rpx;"
							@click="submitInStock('delete-all')" type="default" v-if="editorType == 'add'">清空列表</button>
							
						<button :disabled="false" clsss="batch-submit"
							style="height: 160rpx;margin-right: 20rpx;line-height: 160rpx;min-width: 300rpx;"
							@click="onSelect('inventory-type')" v-if="editorType == 'add' && this.config.serviceName.indexOf('srvretail_inventory_') !== -1">{{activeInventoryType }}</button>
						<button :disabled="listData.length == 0" type="primary" clsss="batch-submit g-button"
							style="height: 160rpx;margin-right: 20rpx;line-height: 160rpx;min-width: 300rpx;"
							@click="submitInStock('save')" v-if="editorType == 'add'">保存</button>
						<button :disabled="listData.length == 0" type="primary" clsss="batch-submit g-button"
							style="height: 160rpx;margin-right: 20rpx;line-height: 160rpx;min-width: 300rpx;"
							@click="submitInStock('submit')" v-if="editorType !== 'detail'">提交</button>
					</view> -->
				</view>
			</view>
		</uni-row>
		<uni-popup ref="popupUpdate" type="center" :mask-click="false">
			<uni-card style="overflow: inherit;">
				<template v-slot:title>
					<view class="flex solid-bottom padding-lg justify-between text-lg">
						<view class="text-lg">{{checkedItem.goods_name}}</view>
						<text class="cuIcon-close" @click="close"></text>
					</view>
				</template>
				<view class="uni-body uni-mt-5">
					<view class="item-update flex padding justify-between">
						<view class="item-update-left padding" style="width:25vw">
							<uni-forms :modelValue="formData" :label-width="'15rem'">
								<uni-forms-item v-show="fieldInUpdateColumns(field.columns)" :label="field.label"
									:name="field.columns" v-for="(field,l) in checkedItemUpdateModel" :key="l">
									<view class="" v-for="(column,index) in config.popupColumns" :key="index"
										v-if="column == field.columns">
										<uni-easyinput @focus="changeFormItem(column)"
											:disabled="['subtotal_amount','cost_price','profit_loss_amount','goods_stock','profit_loss_num','inventory_type'].includes(column)"
											v-if="column == field.columns && (field.type == 'number' ||  field.type == 'digit')"
											v-model="formData[column]" placeholder="" type="text" />
										<uni-data-select v-if="column == field.columns && field.col_type == 'Enum'"
											v-model="formData[column]" :localdata="field._options"></uni-data-select>
									</view>
								</uni-forms-item>

							</uni-forms>
						</view>
						<view class="item-update-right" style="width:25vw">
							<gKeyboard :defaultValue="formData[formItemActive]" @on-value-change="keyUserInValue">
							</gKeyboard>
						</view>
					</view>
				</view>
				<view slot="actions" class="card-actions padding-lg border-top">
					<!-- <view class="card-actions-item padding cu-btn round line-red" @click="actionsClick('delete')" v-if="inPageType !== 'batch-update'">
						<text class="cuIcon-delete" size="18" color="#999"></text>
						<text class="card-actions-item-text">删除</text>
					</view> -->
					<view class="card-actions-item  padding-lg cu-btn round line-black margin-right" @click="close">
						<!-- <uni-icons type="heart" size="18" color="#999"></uni-icons> -->
						<text class="card-actions-item-text">取消</text>
					</view>
					<view class="card-actions-item padding-lg cu-btn round line-cyan margin-right"
						@click="actionsClick('submit')">
						<!-- <uni-icons type="chatbubble" size="18" color="#999"></uni-icons> -->
						<text class="card-actions-item-text">确认</text>
					</view>
				</view>
			</uni-card>
		</uni-popup>
		<view>
			<!-- 操作确认 -->
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog :type="'info'" cancelText="取消" confirmText="同意" title="确认操作!" content=""
					@confirm="dialogConfirm(true)" @close="dialogClose"></uni-popup-dialog>
			</uni-popup>

			<!-- 选择盘点类型 -->
			<uni-popup ref="selectType" type="dialog">
				<uni-popup-dialog :type="'info'" cancelText="取消" confirmText="同意" title="盘点类型" content=""
					@confirm="selectConfirm(true)">
					<view class="uni-px-5">
						<!-- <view class="text">单选选中：{{JSON.stringify(radio2)}}</view> -->
						<uni-data-checkbox mode="button" v-model="activeInventoryType" :localdata="inventoryType">
						</uni-data-checkbox>
					</view>

				</uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import rFilter from '@/components/retail-list/retail-filter.vue'
	import rpaging from '@/components/bx-pagination/bx-pagination.vue'
	import gKeyboard from '@/components/g-batch-update/g-num-keyboard.vue'
	import gStrIntercept from '@/components/g-batch-update/strIntercept.vue'
	export default {
		name: "g-batch-update",
		components: {
			rFilter,
			rpaging,
			gKeyboard,
			gStrIntercept
		},
		data() {
			return {
				mainV2: null, // 主表service v2
				inventoryType: [{
					text: "覆盖",
					value: "覆盖"
				}, {
					text: "累加",
					value: "累加"
				}],
				activeInventoryType: "覆盖",
				mainV2Loaded: false,
				childAddFieldsModel: null, // 子表新增v2
				childAddFieldsModelLoaded: false, // 子表 新增 v2
				serviceV2: {},
				configLoaded: false,
				listDataLoaded: false,
				listData: [],
				searchVal: "",
				tabsBuild: false,
				tabs: [],
				filterCondition: [],
				relation_Conditions: {},
				checkedItem: null,
				checkedItemUpdateModel: [],
				detailLoaded: false, // 详情部分是否加载
				defaultData: null,
				listpage: {
					pageNo: 1,
					rownumber: 500
				},
				more: 'noMore', // more/loading/noMore
				triggered: false,
				relationCondition: null, // 过滤条件
				tabsType: "request", //request  custom
				faceListDataFields: [],
				loading: false,
				popupColumns: ["warehousing_num", "sale_price", "subtotal_amount"],
				formData: {
					// "warehousing_num":"",
					// "sale_price":"",
					// "subtotal_amount":""
				},
				formItemActive: "",
				submitAlertDialog: "", // 点击
				form: {

				}
			};
		},
		props: {
			editorType: {
				type: String,
				default: function() {
					return "add"
				}
			},
			config: {
				type: Object,
				default: function() {
					return {
						serviceName: "srvretail_member_info_select",
						listLayout: "listAndDetail", // listAndDetail listAndFilter  list
						detailPath: "simple", //  simple  基础的； 或者配置页面路由 路由格式待定
						popupColumns: ["warehousing_num", "sale_price", "subtotal_amount"],
						page: {
							pageNo: 1,
							rownumber: 20
						},
					}
				}
			},
			inPageType: {
				type: String,
				default: function() {
					return "add"
				}
			},
			columnRowConfig: {
				type: [Array],
				default: function() {
					return []
				}
			},
			heightTop: {
				type: String,
				default: function() {
					return "60px"
				}
			},
			searchValKey: {
				type: String,
				default: function() {
					return ""
				}
			},
			condition: {
				type: Array,
				default: function() {
					return []
				}
			},
			custGridHeader: {
				type: Array,
				default: function() {
					return []
				}
			}
		},
		computed: {

			childServiceBuild: function() {
				let srv = false
				let main = this.mainV2
				if (main && main.hasOwnProperty('child_service')) {
					let childList = main.child_service
					if (childList.length > 0) {
						for (let child of childList) {
							let foreignKey = child.foreign_key
							if (foreignKey.referenced_table_name == main.main_table) {
								srv = this.deepClone(child)
							}
						}
					}
				}
				return srv
			},
			custTabsRun: function() {
				let cfg = this.config.custTabs || []
				return cfg
			},
			moreRun: function() {
				let more = this.more
				let page = this.listpage
				page.pageNo * page.rownumber < page.total ? more == 'more' : 'noMore'
				return more
			},
			gridHeader: function() {
				let self = this
				let cols = this.serviceV2 ? this.serviceV2._fieldInfo : []
				let addColsModel = this.childAddFieldsModel ? this.childAddFieldsModel._fieldInfo : []
				// let res = [{
				//   columns: "goods_name",
				//   label: "商品名称",
				//   value: null,
				// }, {
				//   columns: "goods_price",
				//   label: "商品单价",
				//   value: null,
				// }, {
				//   columns: "goods_num",
				//   label: "销售数量",
				//   value: null,
				// }, {
				//   columns: "subtotal_amount",
				//   label: "销售金额",
				//   value: null,
				// }, {
				//   columns: "refund_num",
				//   label: "退款数量",
				//   value: null,
				// }, {
				//   columns: "refund_subtotal",
				//   label: "退款金额",
				//   value: null,
				// }]
				let res = [{
					columns: "goods_name",
					label: "商品名称",
					value: null,
				}, {
					columns: "sale_price",
					label: "商品单价",
					value: null,
				}, {
					columns: "goods_num",
					label: "销售数量",
					value: null,
				}, {
					columns: "subtotal_amount",
					label: "销售金额",
					value: null,
				}, {
					columns: "refund_num",
					label: "退款数量",
					value: null,
				},
    //     {
				// 	columns: "ctual_amount",
				// 	label: "退款金额",
				// 	value: null,
				// },
        {
        	columns: "refund_amount",
        	label: "退款金额",
        	value: 0,
        }]
				let confHeader = this.custGridHeader

				// cols = cols.filter((item) => item.in_list !== 0)
				// listHeaders:['goods_name','goods_price','goods_num','subtotal_amount','refund_num','refund_subtotal']

				return res || []
			},
			conditionRun: function() {
				let cond = this.condition.concat(this.filterCondition)
				return cond
			},
			gridButton: function() {
				let buts = this.serviceV2.gridButton || []
				buts = buts.filter((item) => item.button_type == 'add')
				return buts || []
			},
			cols: function() {
				let buts = this.serviceV2.srv_cols || []
				buts = buts.filter((item) => item.in_list == 1)
				return buts || []
			},

			relationConditionRun: function() {
				let relationCondition = {}
				let filterRelation = this.relationCondition
				let headerinputSearch = this.relation_Conditions
				if (filterRelation && filterRelation.data && filterRelation.data.length > 0) {
					relationCondition['data'] = filterRelation['data']
					relationCondition['relation'] = "AND"
					if (headerinputSearch && headerinputSearch.data && headerinputSearch.data.length > 0) {
						relationCondition['data'] = filterRelation['data'].concat(headerS.data)
					}
				}


				return relationCondition
			}
		},
		created() {
			this.getPageConfig()
			console.log("列表加载了--", this.config)
			if (this.inPageType == 'list') {

			} else if (this.inPageType == 'batch-update') {

			}
		},

		methods: {
      onchange(index){
        setTimeout(()=>{
          this.listData = this.listData.map((item,i)=>{
            if(i===index){
              item.refund_amount = (item.ctual_amount*item.refund_num/item.goods_num)||0
            }
            return item
          })
        })
        this.$emit('change',this.listData)
      },
			onSearch() {

			},
			batchUpdateDataRun() {
				let datas = []
				let reqs = []
				let updateCols = this.config.popupColumns
				if (this.inPageType == 'batch-update' && this.config.serviceName == 'srvretail_stock_warning_select') {
					this.listData.forEach((item) => {
						let oldData = item['_oldData']
						let isUpdateed = false
						let req = {
							"serviceName": "srvretail_stock_warning_update",
							"data": [{}],
							"condition": [{
								"colName": "id",
								"value": 60,
								"ruleType": "eq"
							}]
						}
						for (let col of updateCols) {
							if (item[col] !== oldData[col]) {
								req.data[0][col] = item[col]
								req.condition[0].value = item.id
								isUpdateed = true
							}
						}
						if (isUpdateed) {
							reqs.push(req)
						}
					})
				}

				return reqs
			},
			onSelect() {
				this.$refs.selectType.open()
			},
			fieldInUpdateColumns(col) {
				let cols = []
				cols = this.config.popupColumns.filter((item) => item == col)
				return cols.length > 0
			},
			changeFormItem(col) {
				this.formItemActive = col
			},
			buildFormDataColumn(cols) {
				for (let col of cols) {
					this.$set(this.formData, col, '0')
					// this.formData[col] = 0
				}
				// console.log('buildFormDataColumn',this.deepClone(this.formData))
				this.formItemActive = this.config.popupColumns[0]
			},
			getPageConfig() {
				let self = this
				this.getServiceV2(this.config.childService, 'select', 'detaillist').then((res) => {
					console.log("res====>", res)
					this.serviceV2 = res
					this.configLoaded = true
					this.childBuildAddFields()
					this.getListData(1)
				})
			},

			childBuildAddFields() {
				let self = this
				let childAddFieldsModel = null
				let childSrv = self.config.childService.replace("select", 'update')

				if (!self.childAddFieldsModelLoaded) {
					self.getServiceV2(childSrv, 'update', 'update').then((res) => {
						self.$set(self, 'childAddFieldsModel', res)
						// self.childAddFieldsModel = res
						self.childAddFieldsModelLoaded = true
						// if(this.serviceV2.tabs && this.tabsType == 'request'){
						// 	this.buildSections(this.serviceV2.tabs)
						// }else if(this.tabsType == 'custom' && this.config.custTabs){
						// 	this.buildSections(this.config.custTabs,'custom')
						// }
						// this.getListData(1)
					})
				}
			},
			getListData(pageNo, type) {
				let self = this
				this.loading = true
				let srv = 'srvretail_order_detail_select'
				let cond = this.editorType !== 'add' && this.inPageType != 'batch-update' ? [{
					colName: self.config.childKeyCol,
					ruleType: "eq",
					value: self.config.childKeyVal
				}] : this.conditionRun
				let listType = type || 'swipe'
				let req = this.selectRequestObjs(srv, cond, null, this.relationConditionRun)
				// delete this.listpage.total
				req["page"] = this.listpage ? this.listpage : {
					pageNo: 1,
					rownumber: 500
				}
				if (pageNo) {
					req.page.pageNo = pageNo
				}
				if (self.serviceV2 && this.configLoaded) {
					this.$fetch('select', srv, req).then((res) => {
						if (res.success) {
              res.data = res.data.map(item=>{
                if(this.editorType!=='part'){
                  item.refund_amount = item.ctual_amount;
                }
                return item
              })
							if (pageNo !== 1 && pageNo !== null && pageNo !== undefined && listType ==
								'swipe') {
								this.listData = this.listData.concat(res.data)
							} else {
								this.listData = []
								this.listData = res.data
							}
							if (this.inPageType == 'batch-update') {
								this.listData = this.listData.map((item) => {
									item['_oldData'] = self.deepClone(item)
									return item
								})
							}
							console.log("order detail select ", res.data)
							self.$set(self.listpage, 'pageNo', res.page.pageNo)
							self.$set(self.listpage, 'rownumber', res.page.rownumber)
							self.$set(self.listpage, 'total', res.page.total)
							if (res.page.pageNo * res.page.rownumber < res.page.total) {
								self.more = "more"
							} else {
								self.more = "noMore"
							}
							this.loading = false
							self.triggered = false
						}
					})
				}

				this.loading = false

			},
			onGridButton(e) {
				// let url = `/pages/public/form/form?serviceName=${e.service_name}&type=add`
				// if(e.button_type == 'add'){

				// 	switch (e.service_name){
				// 		case "srvretail_warehousing_add":
				// 			url = `/pages/main/stockmgt/stock-batch-submit?serviceName=${e.service_name}&type=add`
				// 			break;
				// 		default:


				// 			break;
				// 	}
				// 	uni.navigateTo({
				// 	  url
				// 	})
				// }else{

				// }
			},

			onItemClick(e) {
				let self = this
				this.detailLoaded = false
				let updateData = this.deepClone(e)
				let heads = this.gridHeader
				this.$set(this, 'checkedItem', updateData)
				if (this.config.serviceName == 'srvretail_order_select' && false) {
					for (let head of heads) {
						for (let cfgcol of self.config.popupColumns) {
							if (cfgcol == head.column && cfgcol == 'inventory_type') {
								if (head.init_expr && (head.init_expr == "mainData.inventory_type")) {
									updateData[cfgcol] = self.activeInventoryType
								}
							}
							self.$set(self.formData, cfgcol, updateData[cfgcol])
						}
						for (let col in updateData) {
							self.$set(self.formData, col, updateData[col])
						}
					}

					// for (let col of self.config.popupColumns) {
					// 	self.$set(self.formData, col, updateData[col])
					// }
					// this.checkedItem = e
					this.$nextTick(() => {
						// this.$emit("on-list-item-checked",e)
						this.$refs.popupUpdate.open()
						this.detailLoaded = true
					})
					this.checkedItemUpdateModel = this.setFieldsDefaultVal(this.childAddFieldsModel._fieldInfo, updateData)
					this.checkedItemUpdateModel = this.checkedItemUpdateModel.map((item) => {
						if (item.col_type == 'Enum') {
							item['_options'] = item.options.map((opt) => {
								opt['text'] = opt.value
								return opt
							})

						}
						return item
					})
				}

				// console.log("--",this.checkedItemUpdateModel, e,self.formData,self.activeInventoryType,heads)

			},
			close() {

				// this.showLayout = false
				// this.$emit("on-select-change",this.selectedDatasRun)
				this.$refs.popupUpdate.close()
			},
			scroll(e) {
				// console.log(e)
			},
			buildSections(tabs, type) { // type custom request  
				// generate tab.condition, order, depend_sections from json string to js object/array
				console.log("buildSections", tabs)
				let self = this
				let tab = {}
				let tabsData = []
				if (type && type == 'custom') {
					tabs.forEach((t, index) => {
						tab = {
							service: null,
							table_name: null,
							orders: null,
							conditions: null,
							seq: null,
							parent: null,
							label: null,
							list_tab_no: null,
							more_config: null,
							inputType: null
						}
						tab.service = t.service || ''
						tab._colName = t.colName.split(',') || null
						tab._type = t.type || null
						tab.inputType = t.inputType || null
						tab.colspan = t.colspan
						tab.label = t.label
						tab.placeholder = t.placeholder || t.type === 'Select' ? '请选择' : '请输入'
						tab.showAllTag = t.showAllTag || false
						tab.list_tab_no = t.list_tab_no || 'custom' + index
						tab._data = t
						tab.showLabel = t.showLabel
						tab.appendSearchButton = t.appendSearchButton || false
						tab._options = [] // 选项列表数据
						tab.option_list = t.options || null // 配置
						if (tab._colName) {
							let cols = tab._colName
							let srvCols = self.cols
							tab['_colSrvData'] = []
							// console.log("tab",tab)
							for (let c = 0; c < cols.length; c++) {
								for (let cs = 0; cs < srvCols.length; cs++) {
									if (cols[c] === srvCols[cs].columns) {
										tab._colSrvData.push(srvCols[cs])
									}
								}
							}

						}
						if (tab.inputType == 'fk') {

						} else if (tab.inputType == 'enum' && tab._colSrvData.length > 0) {
							let colOptions = tab._colSrvData[0].option_list_v2
							tab._options = colOptions.map((item) => {
								let itemVal = {
									text: item.label,
									value: item.value
								}
								return itemVal
							})
						}
						tabsData.push(tab)
					})
				} else {
					tabs.forEach((t) => {
						tab = {
							service: null,
							table_name: null,
							orders: null,
							conditions: null,
							seq: null,
							parent: null,
							label: null,
							list_tab_no: null,
							more_config: null,
							inputType: null
						}

						let mc = JSON.parse(t.more_config)
						// console.log("JSON.parse",t.more_config,JSON.parse(t.more_config))
						tab.more_config = JSON.parse(t.more_config)
						tab.service = t.service
						tab.table_name = t.table_name
						tab.conditions = mc.option_list ? mc.option_list.conditions : null || []
						tab.orders = t.orders
						tab.default = mc.default
						tab.seq = t.seq
						tab.label = t.label
						tab.list_tab_no = t.list_tab_no
						tab._data = t
						tab._options = []
						tab._type = mc.type || null
						tab.option_list = JSON.parse(t.more_config).option_list || null
						tab._colName = mc.colName || null
						tab.inputType = mc.inputType || null
						tab.showAllTag = mc.showAllTag || false
						tab.default = mc.default || '',
							tab.placeholder = mc.placeholder || mc.type === 'select' ? '请选择' : '请输入'
						tab.remoteMethod = ""

						if (tab._colName) {
							tab._colName = tab._colName.split(',')
							let cols = tab._colName
							let srvCols = self.cols
							tab['_colSrvData'] = []
							// console.log("tab",tab)
							for (let c = 0; c < cols.length; c++) {
								for (let cs = 0; cs < srvCols.length; cs++) {
									if (cols[c] === srvCols[cs].columns) {
										tab._colSrvData.push(srvCols[cs])
									}
								}
							}

						}
						if (tab.inputType == 'fk') {
							let cond = [{
								"colName": tab.option_list.key_disp_col,
								"ruleType": "[like]",
								"value": ''
							}]
							cond = cond.concat(tab.option_list ? tab.option_list.conditions : [])
							// cond.push(tab.option_list.conditions)
							console.log("build option ", tab)
							let req = this.selectRequestObjs(tab.option_list.serviceName, cond, null, this
								.relationCondition)
							let options = []
							this.$fetch('select', tab.option_list.serviceName, req).then((res) => {
								let resData = res.data.data
								for (let i = 0; i < resData.length; i++) {
									let item = resData[i]
									let opt = {
										value: item[tab.option_list.refed_col],
										label: item[tab.option_list.key_disp_col]
									}
									options.push(opt)

								}

								// self.formModel[e.list_tab_no]['options'] = options
								tab["_options"] = options
								tab["page"] = res.data.page
								// return options
								console.log("options", options)
								//  resolve(options)
							})
						}
						tabsData.push(tab)
					})
				}

				if (tabsData.length > 0 && !self.tabsBuild) {
					self.tabs = tabsData
					self.tabsBuild = true
				}
			},
			onFilterChange(e) {
				let self = this
				// this.onInputValue = e
				if (e && self.$refs.filterTabs) {
					let tabsConds = self.$refs.filterTabs.buildConditions()
					self.relationCondition = tabsConds
				}
			},
			getTableDatas() {
				let self = this
				let tabsConds = self.$refs.filterTabs ? self.$refs.filterTabs.buildConditions() : {}
				// this.$set('relationCondition',tabsConds)
				this.relationCondition = tabsConds
				// this.listpage.pageNo = 0
				this.$nextTick(() => {
					this.getListData(1)
				})

				//console.log("tabsConds",tabsConds)
			},
			onpagintion(e) {
				console.log("onpagintion", e)
				this.getListData(e, "pagintion")
			},
			onBatchSelect(e) {
				console.log("onBatchSelect1", e)
				let self = this
				let importData = e
				let datas = []
				let heads = self.gridHeader
				console.log("onBatchSelect2", heads)
				let defaultData = self.listData
				let addModel = this.childAddFieldsModel ? this.childAddFieldsModel.srv_cols : []
				let listDatasKeys = defaultData.map((item) => item.goods_no)
				// self.listData = datas.map(item => item)
				if (self.config.defaultData == 'batch-select') {
					for (let imp of importData) {

						let data = {
							_trager: 'add',
							_default: self.deepClone(imp)
						}
						for (let h of heads) {
							if ('inventory_type' == h.columns && h.init_expr == 'mainData.inventory_type') {
								// 处理添加数据的 盘点类型
								imp['inventory_type'] = this.activeInventoryType
								data['inventory_type'] = this.activeInventoryType
							}
							if (h.redundant && h.redundant.dependField == 'goods_no') {
								data[h.columns] = imp[h.redundant.refedCol]
							} else if (h.columns !== 'id' && h['in_' + this.editorType] !== 0) {
								data[h.columns] = imp[h.columns]
							}
						}
						// listDatasKeys =listDatasKeys.concat()
						if (listDatasKeys.indexOf(data.goods_no) == -1) {
							datas.push(self.deepClone(data))
						}

					}
					datas = datas.concat(self.listData)
					self.listData = datas
					// self.faceListDataFields = self.deepClone(self.setFieldsDefaultVal(self.serviceV2._fieldInfo,self.listData))
				}

			},
			keyUserInValue(e) {
				console.log("keyUserInValue", e)
				this.popupUpdateFormModelIn(this.formItemActive, e)
			},
			popupUpdateFormModelIn(col, val) {
				// 键盘输入数据更新到 弹窗 form  model 
				let self = this
				let defaultData = self.defaultData
				let mainSrv = this.config.serviceName
				let modelKeys = Object.keys(self.formData)

				let heads = this.gridHeader
				switch (mainSrv) {
					case 'srvretail_inventory_add':
						// self.$set(self.formData, col, val)
						// console.log(head.column,head)
						this.$set(self.formData, col, val)
						for (let head of heads) {

							if (head.hasOwnProperty('redundant') && head.redundant && head.redundant.hasOwnProperty(
									'func') && head
								.redundant.func) {
								for (let formCol of modelKeys) {
									if (formCol == head.column) {
										let data = self.formData
										let func = head.redundant.func
										let val = eval("var zz=" + func + "(data); zz")

										console.log(head.column, data, val, func)
										// item[head.column] = val
										this.$set(self.formData, head.column, val)
									}
								}
							}

						}
						break;
					case 'srvretail_loss_reporting_add':
						// self.$set(self.formData, col, val)
						this.$set(self.formData, col, val)
						for (let head of heads) {

							console.log('popupUpdateFormModelIn', head.column, head, heads, self.formData)
							if (head.hasOwnProperty('redundant') && head.redundant && head.redundant.hasOwnProperty(
									'func') && head
								.redundant.func) {
								for (let formCol of modelKeys) {
									if (formCol == head.column) {
										let data = self.formData
										let func = head.redundant.func
										let newFun = new Function('data', 'return ' + func + '(data)')
										let val = newFun(data).toFixed(2)
										// let val = eval("var zz=" + func + "(data); zz(data)")

										console.log(head.column, val, self.formData)
										// item[head.column] = val
										this.$set(self.formData, head.column, val)
									}
								}
							}

						}
						break;
					case 'srvretail_stock_warning_select':
						// self.$set(self.formData, col, val)
						this.$set(self.formData, col, val)
						for (let head of heads) {

							// console.log('popupUpdateFormModelIn',head.column,head,heads,self.formData)
							if (head.hasOwnProperty('redundant') && head.redundant && head.redundant.hasOwnProperty(
									'func') && head
								.redundant.func) {
								for (let formCol of modelKeys) {
									if (formCol == head.column) {
										let data = self.formData
										let func = head.redundant.func
										let newFun = new Function('data', 'return ' + func + '(data)')
										let val = newFun(data).toFixed(2)
										// let val = eval("var zz=" + func + "(data); zz(data)")

										console.log(head.column, val, self.formData)
										// item[head.column] = val
										this.$set(self.formData, head.column, val)
									}
								}
							}

						}
						break;
					default:
						self.$set(self.formData, col, val)
						self.$set(self.formData, self.formData[self.config.popupColumns[self.config.popupColumns.length -
							1]], ((
							self.formData[self.config.popupColumns[0]] == undefined ? 0 : self.formData[self
								.config
								.popupColumns[0]]) * (self.formData[self.config.popupColumns[1]] == undefined ?
							0 : self.formData[
								self.config.popupColumns[1]])).toFixed(2))
						break;
				}

			},
			listDataSum(col, datas) {
				let colVal = 0
				let list = datas || []
				let colName = col || ""
				list.forEach((item) => {
					colVal = colVal + (item[colName] ? Number(item[colName]) : 0)
				})
				return colVal
			},
			actionsClick(type) {
				let btnType = type || ''
				let self = this
				let itemBarcode = self.checkedItem ? self.checkedItem['goods_barcode'] : ""
				let formModel = self.formData
				switch (btnType) {
					case 'submit':
						self.listData.forEach((item, index) => {
							// console.log("actionsClick forEach", self.deepClone(item), self.deepClone(self.formData))
							if (item['goods_barcode'] == itemBarcode) {
								for (let col in formModel) {
									// console.log(self.deepClone(formModel))
									item[col] = formModel[col]

								}

								self.$set(self.listData, index, item)
								// console.log("actionsClick", item, self.formData)
							}
						})

						self.close()
						break;
					case 'delete':
						self.listData = self.listData.filter(item => item['goods_barcode'] !== itemBarcode)
						self.close()
						break;
					default:
						break;
				}
			},
			dialogConfirm(confirm) {
				let type = this.submitAlertDialog || ''
				this.submitInStock(type, confirm)
			},
			selectConfirm(confirm) {
				console.log('activeInventoryType', this.activeInventoryType)
				this.buildListRedundant()
				// let type = this.submitAlertDialog || ''
				// this.submitInStock(type, confirm)
			},
			buildRequestData() {
				let datas = this.listData
				console.log('buildRequestData datas', self.defaultData)
				return datas.map((item) => {
					if (item._trager == 'add') {
						item['goods_no'] = item._default["goods_no"]
						delete item._trager
						delete item._default
					}
					return item

				})
			},
			submitRequest(type) {
				let self = this
				let actionType = type || ''
				let srv = self.defaultData ? "srvretail_warehousing_update" : "srvretail_warehousing_add"
				let req = []
				let referenced_column_name
				let keydispcol = self.childServiceBuild ? self.childServiceBuild.foreign_key.keydispcol : ""
				let referencedColumnName = self.childServiceBuild ? self.childServiceBuild.foreign_key
					.referenced_column_name : ""
				let childSrv = this.serviceV2.service_name.replace("select", this.editorType)
				console.log('batchUpdateDataRun', self.batchUpdateDataRun)
				if ((actionType == 'save' || actionType == 'submit') && !self.defaultData && self.inPageType !==
					'batch-update') {
					srv = this.config.serviceName
					req = [{
						"serviceName": this.config.serviceName,
						"condition": [],
						"data": [{

							"child_data_list": [{
								"serviceName": childSrv,
								"condition": [],
								"depend_keys": [{
									"type": "column",
									"add_col": keydispcol,
									"depend_key": referencedColumnName
								}],
								"data": self.buildRequestData()
							}]
						}]
					}]
					switch (srv) {
						case 'srvretail_warehousing_add':
							req[0].data[0]["warehousing_amount"] = self.listDataSum('subtotal_amount', self.listData)
							req[0].data[0]["operator"] = uni.getStorageSync('login_user_info').user_no
							req[0].data[0]["warehousing_state"] = actionType == 'save' ? "待提交" : actionType == "submit" ?
								'已提交' : '待提交'
							break;
						case 'srvretail_issue_add':
							req[0].data[0]["issue_amount"] = self.listDataSum('subtotal_amount', self.listData)
							req[0].data[0]["operator"] = uni.getStorageSync('login_user_info').user_no
							req[0].data[0]["issue_state"] = actionType == 'save' ? "待提交" : actionType == "submit" ? '已提交' :
								'待提交'
							break;

						case 'srvretail_inventory_add':
							req[0].data[0]["profit_loss_amount"] = self.listDataSum('profit_loss_amount', self.listData)
							req[0].data[0]["inventory_type"] = self.activeInventoryType
							req[0].data[0]["operator"] = uni.getStorageSync('login_user_info').user_no
							req[0].data[0]["inventory_state"] = actionType == 'save' ? "待提交" : actionType == "submit" ?
								'已提交' :
								'待提交'
							break;

						case 'srvretail_loss_reporting_add':
							req[0].data[0]["loss_amount"] = self.listDataSum('loss_amount', self.listData)
							req[0].data[0]["operator"] = uni.getStorageSync('login_user_info').user_no
							req[0].data[0]["loss_state"] = actionType == 'save' ? "待提交" : actionType == "submit" ? '已提交' :
								'待提交'
							break;
						case 'srvretail_stock_warning_select':
							if (self.inPageType == 'batch-update') {
								// req = self.deepClone(self.batchUpdateDataRun) 
							}
							break;
						default:
							break;
					}
				} else if (actionType == 'submit' && self.inPageType !== 'batch-update') {

					srv = this.config.serviceName
					req = [{
						"serviceName": this.config.serviceName,
						"condition": [{
							"colName": "id",
							"ruleType": "eq",
							"value": self.defaultData[0].id
						}],
						"data": [{
							// "warehousing_state": "已提交"
						}]
					}]
					switch (srv) {
						case 'srvretail_warehousing_update':
							req[0].data[0]["warehousing_state"] = '已提交'
							break;
						case 'srvretail_issue_update':
							req[0].data[0]["issue_state"] = '已提交'
							break;
						case 'srvretail_inventory_update':
							req[0].data[0]["inventory_state"] = '已提交'
							break;
						case 'srvretail_loss_reporting_update':
							req[0].data[0]["loss_state"] = '已提交'
							break;
						default:
							break;
					}
				} else if (self.config.serviceName == 'srvretail_stock_warning_select' && self.inPageType ==
					'batch-update') {
					srv = 'srvretail_stock_warning_update'
					req = self.batchUpdateDataRun()
					if (req.length == 0) {
						uni.showToast({
							icon: "none",
							title: '暂无可提交数据'
						})
						return
					}
				}

				self.$fetch('operate', srv, req).then((res) => {
					if (res.success) {
						self.dialogClose()
						if (self.inPageType !== 'batch-update') {
							uni.navigateBack()
						} else {
							self.getTableDatas()
						}

					} else {
						uni.showToast({
							icon: "none",
							title: res.resultMessage
						})
					}
				})
			},
			submitInStock(type, confirm) {
				let self = this
				this.submitAlertDialog = type
				let actionType = type || ''

				switch (actionType) {
					case 'delete-all':
						self.$refs.alertDialog.open()
						if (confirm) {
							self.listData = self.listData.filter(item => item['goods_barcode'] == "###")
						}

						break;
					case 'save':
						self.$refs.alertDialog.open()
						if (confirm) {
							self.submitRequest(actionType)
						}

						break;
					case 'submit':
						self.$refs.alertDialog.open()
						if (confirm) {
							self.submitRequest(actionType)
						}
						break;
					default:
						break;
				}
				console.log("submitInStock", type, confirm)
			},
			dialogClose() {
				let self = this
				self.$refs.alertDialog.close()
				self.submitAlertDialog = ""
			},
			buildListRedundant(newVal) {
				let list = this.listData
				let fields = this.gridHeader
				for (let i = 0; i < list.length; i++) {
					list[i]['inventory_type'] = this.activeInventoryType
					// console.log("activeInventoryType change",i,list[i])
					this.$set(this.listData, i, list[i])
				}
				for (let head of fields) {
					if (head.init_expr) {

					}
					if (head.hasOwnProperty('redundant') && head.redundant && head.redundant.hasOwnProperty('func')) {
						for (let item of list) {
							let data = item
							let func = head.redundant.func
							let val = eval("var zz=" + func + "(data, this); zz")

							// console.log(item,head.column,data,val)
							item[head.column] = val
							this.$set(item, head.column, val)
						}
					}
				}
			},
			getTableData() {
				return this.listData
			}
		},
		watch: {
			"activeInventoryType": {
				handler: function(newVal, oldVal) {
					if ((newVal !== oldVal) && this.config.serviceName == 'srvretail_inventory_add') {
						// this.buildListRedundant(newVal)
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	$bottom-button-height:8rem;
	$bottom-button-font-size:2rem;
	$middle-body-height:calc(100vh - 16rem);
	$padding:0.5rem 1rem;

	.card-actions {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.card-actions-item {
			font-size: 36rpx;
		}
	}


	::v-deep .u-number-box {
		width: 100%;
		text-align: center;
		justify-content: center;

		.u-number-box__minus,
		.u-number-box__plus {
			height: 6.8rem !important;
			width: 6.8rem !important;
		}
	}


	.retail-list {
		width: 100%;
		// background-color: $retail-color-primary;
		display: flex;
		height: calc(100vh -40rem);
		height: calc(100vh - 16rem);
		flex-direction: row;
		justify-content: space-between;

		.retail-list-block {
			width: 100%;

			.retail-list-left-middle {
				min-height: 90upx !important;

			}
		}

		.retail-list-left {
			padding: 0upx;
			height: 100%;
			width: calc(100vw - 70%);

			.retail-list-left-middle {
				.scroll-left {
					height: calc(100vh - 200rpx);
				}

				&,
				.full-height {
					height: 100%;
				}
			}
		}

		.retail-list-left,
		.retail-list-block {
			// padding: 20upx;
			background-color: #f2f2f2;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.retail-list-left-middle {
				overflow-y: auto;

				.list-item-inline {
					width: 100%;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
				}
			}

			.retail-list-left-top {

				// height: $bottom-button-height;
				.cu-btn.lg {
					height: $bottom-button-height;
					font-size: $bottom-button-font-size;
				}
			}

			.retail-list-left-bottom {

				// height: $bottom-button-height;
				.cu-btn.lg {
					height: $bottom-button-height;
					font-size: $bottom-button-font-size;
				}
			}
		}

		.retail-list-right.retail-list-right-full {
			width: calc(100vw - 30%);
		}

		.retail-list-right {
			// padding: 20upx;
			width: 100%;
			background-color: #f2f2f2;
			display: flex;
			flex-direction: column;
			// height: calc(100vh - 270rpx);
			justify-content: space-between;

			.retail-list-right-top {
				height: 160rpx;
				display: flex;
				flex-direction: row;
				align-items: center;
			}

			.retail-list-right-middle {
				height: 100%;

				.list-item-inline {
					width: 100%;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
				}

				overflow-y: auto;
			}

			.retail-list-right-bottom {
				// height: $bottom-button-height;
				display: flex;
				justify-content: space-between;
				flex-direction: row;



				.buttom-layout {
					display: flex;
					flex-direction: row;

					.count-layout {
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						align-items: center;
						text-align: center;
						font-size: 2.4rem;
						height: 9rem;
						border-right: 2px solid #f2f2f2;

						* {
							min-width: 100%;
						}

						&:last-child {
							border-right: 0;
						}
					}
				}
			}
		}

		.uni-list {
			background-color: #f2f2f2;

			.uni-list-item {
				padding: 20upx;
				margin-bottom: 10upx !important;
			}
		}
	}

	.search-box {
		margin-bottom: 1rem;
		padding: 0;
		display: flex;

		.uni-input-box {
			display: flex;
			align-items: center;
			padding: 0 2rem;
			flex: 1;
			border-radius: 1rem;
			border: 1px solid #E5E5E5;
			font-size: 2.4rem;

			.cuIcon-scan {
				font-size: 3rem;
				// margin-right: 2rem;
				font-weight: bold;
			}
		}

		.search-icon {
			margin-left: 2rem;
			width: 10rem;
			min-width: 10rem;
			border: 1px solid #E5E5E5;
			height: 100%;
			font-weight: bold;
			text-align: center;
			font-size: 2.5rem;

			&.bg-white {
				background-color: #fff;
				color: #333;
			}
		}
	}
</style>
